/**
 * Created by Administrator on 2017/2/23.
 */
function addLoadEvent(callback) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = callback;
    } else {
        window.onload = function () {
            oldonload();
            callback();
        }
    }
}

function insertAfter(newElement, targetElement) {
    var parent = targetElement.parentNode;
    if (parent.lastChild == targetElement) {
        parent.appendChild(newElement);
    } else {
        parent.insertBefore(newElement, targetElement.nextSibling);
    }
}

function addClass(element, value) {
    if (!element.className) {
        element.className = value;
    } else {
        var newClassName = element.className;
        newClassName += ' ';
        newClassName += value;
        element.className = newClassName;
    }
}

function hightlightPage() {
    var supported = document.getElementsByTagName || document.getElementById;
    if (!supported) {
        return false;
    }

    var headers = document.getElementsByTagName('header');
    if (headers.length == 0) {
        return false;
    }

    var navs = headers[0].getElementsByTagName('nav');
    if (navs.length == 0) {
        return false;
    }

    var links = navs[0].getElementsByTagName('a');
    var linkurl;
    for (var i = 0; i < links.length; i++) {
        linkurl = links[i].getAttribute('href');
        if (window.location.href.indexOf(linkurl) != -1) {
            links[i].className = 'here';
            var linktext = links[i].lastChild.nodeValue.toLowerCase();
            document.body.setAttribute('id', linktext);
        }
    }
}

function moveElement(elementId, finalx, finaly, interval) {
    var supported = document.getElementById;
    if (!supported) {
        return false;
    }
    var elem = document.getElementById(elementId);
    if (!elem) {
        return false;
    }
    if (elem.movement) {
        clearTimeout(elem.movement);
    }
    if (!elem.style.left) {
        elem.style.left = '0px';
    }
    if (!elem.style.top) {
        elem.style.top = '0px';
    }
    var postionx = parseInt(elem.style.left);
    var postiony = parseInt(elem.style.top);
    if (postionx == finalx && postiony == finaly) {
        return true;
    }
    if (postionx > finalx) {
        postionx += Math.ceil((finalx - postionx) / 10);
    }
    if (postionx > finalx) {
        postionx += Math.ceil((postionx - finalx) / 10);
    }
    if (postiony > finaly) {
        postiony += Math.ceil((finaly - postiony) / 10);
    }
    if (postiony > finaly) {
        postiony += Math.ceil((postiony - finaly) / 10);
    }
    elem.style.left = postionx + 'px';
    elem.style.top = postiony + 'px';
    var repeat = "moveElement('" + elementId + "', " + finalx + ", " + finaly + ", " + interval + ")";
    elem.movement = setTimeout(repeat, interval);
}

function preparseSlideshow() {
    var supported = document.getElementsByTagName || document.getElementById;
    if (!supported) {
        return false;
    }
    var links = document.getElementsByTagName('a');
    var destination;
    for (var i = 0; i < links.length; i++) {
        links[i].onmouseover = function () {
            destination = this.getAttribute('href');
            if (destination.indexOf('index.html') != -1) {
                moveElement('preview', 0, 0, 5);
            }
            if (destination.indexOf('about.html') != -1) {
                moveElement('preview', -150, 0, 5);
            }
            if (destination.indexOf('photos.html') != -1) {
                moveElement('preview', -300, 0, 5);
            }
            if (destination.indexOf('live.html') != -1) {
                moveElement('preview', -450, 0, 5);
            }
            if (destination.indexOf('contact.html') != -1) {
                moveElement('preview', -600, 0, 5);
            }
        };
    }
}

function showSection(id) {
    var sections = document.getElementsByTagName('section');
    for (var i = 0; i < sections.length; i++) {
        if (sections[i].getAttribute('id') != id) {
            sections[i].style.display = 'none';
        } else {
            sections[i].style.display = 'block';
        }
    }
}

function prepareInternalnav() {
    var supported = document.getElementsByTagName || document.getElementById;
    if (!supported) {
        return false;
    }
    var articles = document.getElementsByTagName('article');
    if (articles.length == 0) {
        return false;
    }
    var navs = articles[0].getElementsByTagName('nav');
    if (navs.length == 0) {
        return false;
    }
    var nav = navs[0];
    var links = nav.getElementsByTagName('a');
    for (var i = 0; i < links.length; i++) {
        var sectionId = links[i].getAttribute('href').split('#')[1];
        var section = document.getElementById(sectionId);
        if (!section) {
            continue;
        }
        section.style.display = 'none';
        links[i].desctination = sectionId;
        links[i].onclick = function () {
            showSection(this.desctination);
            return false;
        }
    }
}

function showPic(whichpic) {
    var placeholder = document.getElementById('placeholder');
    if (!placeholder) {
        return true;
    }
    var source = whichpic.getAttribute('href');
    placeholder.setAttribute('src', source);
    var description = document.getElementById('description');
    if (!description) {
        return false;
    }
    if (description.firstChild.nodeType == 3) {
        description.firstChild.noveValue = title;
    }
    var title = whichpic.getAttribute('title');
    if (!title) {
        title = '';
    }
    return false;
}

function preparePlaceholder() {
    var supported = document.createElement || document.createTextNode || document.getElementById;
    if (!supported) {
        return false;
    }
    var gallery = document.getElementById('image-gallery');
    if (!gallery) {
        return false;
    }
    var placeholder = document.createElement('img');
    placeholder.setAttribute('id', 'placeholder');
    placeholder.setAttribute('src', 'images/placeholder.gif');
    placeholder.setAttribute('alt', 'my image gallery');
    var description = document.createElement('p');
    description.setAttribute('id', 'description');
    var text = document.createTextNode('Choose an image');
    description.appendChild(text);
    insertAfter(description, gallery);
    insertAfter(placeholder, description);
}

function prepareGallery() {
    var supported = document.getElementsByTagName || document.getElementById;
    if (!supported) {
        return false;
    }
    var gallery = document.getElementById('image-gallery');
    if (!gallery) {
        return false;
    }
    var links = gallery.getElementsByTagName('a');
    for (var i = 0; i < links.length; i++) {
        links[i].onclick = function () {
            return showPic(this);
        }
    }
}

function stripeTables() {
    var supported = document.getElementById;
    if (!supported) {
        return false;
    }
    var tables = document.getElementsByTagName('table');
    for (var i = 0; i < tables.length; i++) {
        var odd = false;
        var rows = tables[i].getElementsByTagName('tr');
        for (var j = 0; j < rows.length; j++) {
            if (odd == true) {
                addClass(rows[j], 'odd');
                odd = false;
            } else {
                odd = true;
            }
        }
    }
}

function highlightRow() {
    var supported = document.getElementsByTagName;
    if (!supported) {
        return false;
    }
    var rows = document.getElementsByTagName('tr');
    for (var i = 0; i < rows.length; i++) {
        rows[i].oldClassName = rows[i].className;
        rows[i].onmouseover = function () {
            addClass(this, 'highlight');
        };
        rows[i].onmouseout = function () {
            this.className = this.oldClassName;
        }
    }
}

function displayAbbreviations() {
    var supported = document.getElementsByTagName || document.createElement || document.createTextNode;
    if (!supported) {
        return false;
    }
    var abbreviations = document.getElementsByTagName('abbr');
    if (abbreviations.length < 1) {
        return false;
    }
    var definitions = [];
    for (var i = 0; i < abbreviations.length; i++) {
        var currentAbbr = abbreviations[i];
        if (currentAbbr.childNodes.length < 1) {
            continue;
        }
        var value = currentAbbr.getAttribute('title');
        var key = currentAbbr.lastChild.nodeValue;
        definitions[key] = value;
    }
    var definitionlist = document.createElement('dl');
    for (key in definitions) {
        value = definitions[key];
        var definitiontitle = document.createElement('dt');
        var text = document.createTextNode(key);
        definitiontitle.appendChild(text);
        var definitiondescription = document.createElement('dd');
        text = document.createTextNode(value);
        definitiondescription.appendChild(text);
        definitionlist.appendChild(definitiontitle);
        definitionlist.appendChild(definitiondescription);
    }
    if (definitionlist.length == 0) {
        return false;
    }
    var articles = document.getElementsByTagName('article');
    if (articles.length == 0) {
        return false;
    }
    var container = articles[0];
    container.appendChild(definitionlist);
}

function focusLabels() {
    var supported = document.getElementsByTagName || document.getElementById;
    if (!supported) {
        return false;
    }
    var labels = document.getElementsByTagName('label');
    for (var i = 0; i < labels.length; i++) {
        var labelFor = labels[i].getAttributeNode('for');
        if (!labelFor) {
            continue;
        }
        labelFor.onclick = function () {
            var id = this.getAttribute('for');
            var element = document.getElementById(id);
            element.focus();
        }
    }
}

function resetFields(whichform) {
    if (Modernizr.input.placeholder) {
        return;
    }
    for (var i = 0; i < whichform.length; i++) {
        var element = whichform.elements[i];
        if (element.type == 'submit') {
            continue;
        }
        var check = element.placeholder || element.getAttribute('placeholder');
        if (!check) {
            continue;
        }
        element.onfocus = function () {
            var text = this.placeholder || this.getAttribute('placeholder');
            if (this.value == text) {
                this.className = '';
                this.value = '';
            }
        };
        element.onblur = function () {
            if (this.value = '') {
                this.className = 'placeholder';
                this.value = this.placeholder || this.getAttribute('placeholder');
            }
        };
        element.onblur();
    }
}

function prepareForms() {
    for (var i = 0; i < document.forms.length; i++) {
        var thisform = document.forms[i];
        resetFields(thisform);
        thisform.onsubmit = function () {
            if (!validateForm(this)) {
                return false;
            }
            var article = document.getElementsByTagName('article')[0];
            return submitFormWithAjax(this, article);
        }
    }
}

function isFilled(field) {
    if (field.value.replace(' ', '').length == 0) {
        return false;
    }
    var placeholder = field.placeholder || field.getAttribute('placeholder');
    return field.value != placeholder;
}

function isEmaill(field) {
    return field.value.indexOf('@') != -1 && field.value.indexOf('.') != -1;
}

function validateForm(whichform) {
    for (var i = 0; i < whichform.elements.length; i++) {
        var element = whichform.elements[i];
        if (element.required == 'required') {
            if (isFilled(element)) {
                alert('Please fill in the ' + element.name + ' field.');
                return false;
            }
        }
        if (element.type == 'email') {
            if (isEmaill(element)) {
                alert('The ' + element.name + ' field must be a vaild email address.');
                return false;
            }
        }
    }
    return true;
}

function getHTTPObject() {
    if (typeof XMLHttpRequest == 'undefined') {
        XMLHttpRequest = function () {
            try {
                return new ActiveXObject('Msxml2.XMLHTTP.6.0');
            } catch (e) {
            }
            try {
                return new ActiveXObject('Msxml2.XMLHTTP.3.0');
            } catch (e) {
            }
            try {
                return new ActiveXObject('Msxml2.XMLHTTP');
            } catch (e) {
            }
        };
        return false;
    }
    return new XMLHttpRequest();
}

function displayAjaxLoading(element) {
    while (element.hasChildNodes()) {
        element.removeChild(element.lastChild);
    }
    var content = document.createElement('img');
    content.setAttribute('src', 'images/loading.gif');
    content.setAttribute('alt', 'loading...');
    element.appendChild(content);
}

function submitFormWithAjax(whichform, target) {
    var request = getHTTPObject();
    if (!request) {
        return false;
    }
    displayAjaxLoading(target);
    var dataParts = [];
    var element;
    for (var i = 0; i < whichform.elements.length; i++) {
        element = whichform.elements[i];
        dataParts[i] = element.name + '=' + encodeURIComponent(element.value);
    }
    var data = dataParts.join('&');
    request.open('POST', whichform.getAttribute('action'), true);
    request.setRequestHeader('Content-Type', 'applicaton/x-www-form-urlencoded');
    request.onreadystatechange = function () {
        if (request.readyState == 4) {
            if (request.status == 200 || request.status == 0) {
                var matches = request.responseText.match(/<article>([\s\S+]+)<\/article>/);
                if (matches.length > 0) {
                    target.innerHTML = matches[1];
                } else {
                    target.innerHTML = '<p>Oops, there was an error. Sorry.</p>';
                }
            }
            else {
                target.innerHTML = '<p>' + request.statusText + '</p>';
            }
        }
    };
    request.send(data);
    return true;
}

addLoadEvent(hightlightPage);
addLoadEvent(preparseSlideshow);
addLoadEvent(prepareInternalnav);
addLoadEvent(preparePlaceholder);
addLoadEvent(prepareGallery);
addLoadEvent(stripeTables);
addLoadEvent(highlightRow);
addLoadEvent(displayAbbreviations);
addLoadEvent(focusLabels);
addLoadEvent(prepareForms);